package com.yuan.fmmall.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuan.fmmall.dao.CategoryMapper;
import com.yuan.fmmall.entity.CategoryVO;
import com.yuan.fmmall.entity.IndexImg;
import com.yuan.fmmall.service.CategoryService;
import com.yuan.fmmall.vo.ResStatus;
import com.yuan.fmmall.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Yuan
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public ResultVO listCategories() {
        //用于存放category的List集合
        List<CategoryVO> categoryVOS = null;
        try {
            String cateories = stringRedisTemplate.boundValueOps("cateories").get();
            if (cateories != null) {
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, CategoryVO.class);
                categoryVOS = objectMapper.readValue(cateories, javaType);
            } else {
                //若redis中没有数据，则查询数据库
                categoryVOS = categoryMapper.selectAllCategories();
                String s = objectMapper.writeValueAsString(categoryVOS);
                stringRedisTemplate.boundValueOps("cateories").set(s, 1, TimeUnit.DAYS);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        ResultVO resultVO = new ResultVO(ResStatus.OK, "success", categoryVOS);
        return resultVO;
    }

    @Override
    public ResultVO listCategories2(int parentId) {
        List<CategoryVO> categoryVOS = categoryMapper.selectAllCategories2(parentId);
        ResultVO resultVO = new ResultVO(ResStatus.OK, "success", categoryVOS);
        return resultVO;
    }
}
